package com.useeinfo.oa.modules.security.start;

import com.useeinfo.framework.sugar.tools.Configuration;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.modules.base.biz.ApplicationModuleBiz;
import com.useeinfo.oa.modules.base.biz.EnterpriseBiz;
import com.useeinfo.oa.modules.base.entity.ApplicationModule;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.security.biz.SystemAuthorityBiz;
import com.useeinfo.oa.modules.security.biz.SystemModuleBiz;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.entity.SystemModule;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.enums.OperationRoleEnum;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.web.context.ServletContextAware;

import javax.servlet.ServletContext;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.*;

/**
 * Author: 居泽平  Date: 14/12/20, 21:43
 */
public class InstantiationTracingBeanPostProcessor implements ApplicationListener<ContextRefreshedEvent>, ServletContextAware {

    private final static Logger logger = LoggerFactory.getLogger(InstantiationTracingBeanPostProcessor.class);

    private ServletContext servletContext;

    @Autowired
    private SystemUserBiz systemUserBiz;
    @Autowired
    private ApplicationModuleBiz applicationModuleBiz;
    @Autowired
    private SystemAuthorityBiz systemAuthorityBiz;
    @Autowired
    private EnterpriseBiz enterpriseBiz;
    @Autowired
    private SystemModuleBiz systemModuleBiz;


    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {

        logger.info("我在刚启动时执行-1");

        //以下这段代码在这里是失效的，可用于business中获取当前的Session
        //HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        //这里的『Parent』是否执行，与『web.xml』中的配置有关系
        if (event.getApplicationContext().getParent() == null) {
            //root application context 没有parent，他就是老大.
            //需要执行的逻辑代码，当spring容器初始化完成后就会执行该方法。

            //设定一个名为Application的变量
            servletContext.setAttribute("test", "test");
            logger.info("我在刚启动时执行-2");
        }

        //启动插入第一个公司
        Long superEnterpriseId = StringConverters.ToLong(Configuration.getConfigurationByName("superEnterpriseId"));
        Enterprise enterprise = enterpriseBiz.findModel(superEnterpriseId);
        if (null == enterprise) {
            enterprise = new Enterprise();
            enterprise.setId(superEnterpriseId);
            enterprise.setCreateDate(new Date());
            enterprise.setEnterpriseName("易优服主平台");
            enterprise.setCode("易优服主平台");
            enterprise.setParentIds("," + superEnterpriseId + ",");
            enterpriseBiz.addOrUpdate(enterprise);
        }

        //开始用户
        SystemUser systemUser = new SystemUser("admin", "admin", "超级管理员");
        if (!systemUserBiz.existUserAccount(systemUser)) {
            Set<Enterprise> enterpriseSet = new HashSet<>();
            enterpriseSet.add(enterprise);
            systemUser.setEnterpriseSet(enterpriseSet);
            systemUser.setOperationRole(OperationRoleEnum.admin.getCode());
            systemUserBiz.addOrUpdate(systemUser);
        }

        //启动添加所有的应用到模块
        List<ApplicationModule> applicationModuleList = applicationModuleBiz.findList();
        if (CollectionUtils.isNotEmpty(applicationModuleList)) {
            applicationModuleList.forEach(applicationModule -> {
                if (!systemModuleBiz.existSystemModuleByapplicationId(applicationModule.getId() + "")) {
                    systemModuleBiz.addOrUpdate(new SystemModule(applicationModule.getApplicationName()
                            , applicationModule.getApplicationName(), applicationModule.getId()));
                }
            });
        }



        /*添加默认权限*/
      /*  systemAuthorityBiz.addSystemAuthorityFirst("用户管理");
        systemAuthorityBiz.addSystemAuthorityFirst("角色管理");
        systemAuthorityBiz.addSystemAuthorityFirst("权限管理");*/

        logger.info("我在刚启动时执行-3");
    }

    @Override
    public void setServletContext(ServletContext servletContext) {
        logger.info("我在刚启动时执行-setServletContext");
        this.servletContext = servletContext;
    }
}
